from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.db.postgres import get_session
from app.models import Event
from app.schemas.event import EventCreate, EventRead, EventUpdate
from datetime import datetime, timezone


router = APIRouter(prefix="/events", tags=["events"])


@router.get("", response_model=list[EventRead])
async def list_events(
    activity_id: str | None = Query(default=None),
    session: AsyncSession = Depends(get_session),
):
    stmt = select(Event)
    if activity_id:
        stmt = stmt.where(Event.activity_id == activity_id)
    result = await session.execute(stmt)
    return [EventRead.model_validate(x) for x in result.scalars().all()]


@router.post("", response_model=EventRead)
async def create_event(payload: EventCreate, session: AsyncSession = Depends(get_session)):
    data = payload.model_dump()
    v = data.get("occurred_at")
    if isinstance(v, str) and v:
        try:
            data["occurred_at"] = datetime.strptime(v, "%Y-%m-%d %H:%M:%S")
        except Exception:
            try:
                data["occurred_at"] = datetime.fromisoformat(v)
            except Exception:
                data["occurred_at"] = None
    
    # 处理UUID字段的字符串转换
    for k in ("activity_id", "event_type_id"):
        vv = data.get(k)
        if isinstance(vv, str) and vv.strip() == "":
            data[k] = None
        elif isinstance(vv, str):
            try:
                data[k] = UUID(vv)
            except ValueError:
                data[k] = None
    
    for k in ("location_admin", "location_detail", "attachments_ref_id"):
        vv = data.get(k)
        if isinstance(vv, str) and vv.strip() == "":
            data[k] = None
    
    obj = Event(**data)
    session.add(obj)
    await session.flush()
    await session.refresh(obj)
    await session.commit()
    return EventRead.model_validate(obj)


@router.get("/{event_id}", response_model=EventRead)
async def get_event(event_id: str, session: AsyncSession = Depends(get_session)):
    obj = await session.get(Event, event_id)
    if not obj:
        raise HTTPException(status_code=404, detail="事件不存在")
    return EventRead.model_validate(obj)


@router.put("/{event_id}", response_model=EventRead)
async def update_event(event_id: str, payload: EventUpdate, session: AsyncSession = Depends(get_session)):
    obj = await session.get(Event, event_id)
    if not obj:
        raise HTTPException(status_code=404, detail="事件不存在")
    data = payload.model_dump(exclude_unset=True)
    v = data.get("occurred_at")
    if isinstance(v, str) and v:
        try:
            data["occurred_at"] = datetime.strptime(v, "%Y-%m-%d %H:%M:%S")
        except Exception:
            try:
                data["occurred_at"] = datetime.fromisoformat(v)
            except Exception:
                data["occurred_at"] = None
    # 处理UUID字段的字符串转换
    for k in ("activity_id", "event_type_id"):
        vv = data.get(k)
        if isinstance(vv, str) and vv.strip() == "":
            data[k] = None
        elif isinstance(vv, str):
            try:
                data[k] = UUID(vv)
            except ValueError:
                data[k] = None
    
    for k in ("location_admin", "location_detail", "attachments_ref_id"):
        vv = data.get(k)
        if isinstance(vv, str) and vv.strip() == "":
            data[k] = None
    for k, v in data.items():
        setattr(obj, k, v)
    obj.updated_at = datetime.now(timezone.utc)
    await session.flush()
    await session.refresh(obj)
    await session.commit()
    return EventRead.model_validate(obj)


@router.delete("/{event_id}")
async def delete_event(event_id: str, session: AsyncSession = Depends(get_session)):
    obj = await session.get(Event, event_id)
    if not obj:
        raise HTTPException(status_code=404, detail="事件不存在")
    await session.delete(obj)
    await session.commit()
    return {"ok": True}
